//
//  RightCollectionClickController.m
//  quickLook
//
//  Created by J on 15/9/1.
//  Copyright (c) 2015年 JZJ. All rights reserved.
//

#import "ThirdNaviSearchController.h"


#import "CustomView.h"

#import "NavisearchCell.h"
#import "IntroduceController.h"



@interface ThirdNaviSearchController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSNumber* _number;
    BOOL isLoad;
    
    CustomView* _View;
    CAGradientLayer *_gradientLayer;
    
    UILabel* _attentionLabel;
    BOOL _isSelected;
    BOOL _isExisted;

    UIButton* _leftBackButton;
    
    CGRect _rightFrame;
    
    }
@property (nonatomic, copy) NSString *titleStr;
@property (nonatomic, assign) BOOL isSeleted;

@property (nonatomic, weak) UIButton *orderButton;

@property(nonatomic,strong)    UILabel* attentionLabel;






@property(nonatomic,strong)UIView* lineView;


@property(nonatomic,strong)Model* introductionModel;






@end

@implementation ThirdNaviSearchController


- (NSString *)titleStr
{
    if (!_titleStr) {
        self.titleStr = @"顺序";
    }
    return _titleStr;
}

- (instancetype)initWithFlag:(NSInteger) flag{
    if (self = [super init]) {
        self.flag = flag;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor=[UIColor whiteColor];
    // Do any additional setup after loading the view.
    [self loadData];
    
    [self createUI];
    

}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    
    _tableView.separatorColor=SEPARATORCOLOR;
    
    
    [self.navigationController setNavigationBarHidden:YES];
    [self isExist];

    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
    
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
        [self.navigationController setNavigationBarHidden:NO];
}

- (void)loadData
{
   
    [DownLoad getThirdNavDataWithID:self.model.id  andorder:_i andBlock:^(NSDictionary* obj, NSError * error) {
        
        //刷新tableheaderView
        _introductionModel=[[Model alloc]init];
        
        [_introductionModel setValuesForKeysWithDictionary:obj[@"data"]];
        
        [_View refreshWithModel:_introductionModel];

    
        
        

        if ([_number isEqual:@0]) {
            //下拉刷新
            
            [_tableView.header endRefreshing];

            self.dataArray=[NSMutableArray array];
            
            
        }else{
            [_tableView.footer endRefreshing];
        }
        

        
        NSArray* values=obj[@"data"][@"comics"];
        
        [values enumerateObjectsUsingBlock:^(NSDictionary* dic, NSUInteger idx, BOOL *stop) {
            
            Model* model=[[Model alloc]init];
            
            
        [model setValuesForKeysWithDictionary:dic];
            
            [_dataArray addObject:model];
            
          
        }];
        
        [_tableView reloadData];
        
        isLoad=NO;
        
    }];
    
    
    
    
}

- (void)createUI
{
    

    

    
    
    
    _number=@0;
    
    _currentState=JZJTableViewState_showContent;

    self.automaticallyAdjustsScrollViewInsets=NO;
 
    
    _lineView.frame=CGRectMake(0,29, self.view.frame.size.width/2, 2);

    [self.view bringSubviewToFront:_lineView];
    
    
    if (_isScreen) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];

    }else{
        
        
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-49) style:UITableViewStyleGrouped];

    }
    
    
    _tableView.contentInset=UIEdgeInsetsMake(200, 0, 0, 0);

    _tableView.delegate=self;
    _tableView.dataSource=self;
    
    //设置tableview背景色

    self.tableView.backgroundColor=[UIColor whiteColor];

    [self.view addSubview:_tableView];
    

    //下拉放大imageView
    
    _View=[[NSBundle mainBundle]loadNibNamed:@"CustomView02" owner:nil options:nil][0];

    
    
    _View.frame=CGRectMake(0,-200, self.view.frame.size.width, 200);
    _View.imageView.frame=CGRectMake(0,-200, self.view.frame.size.width, 200);
    _View.imageView.contentMode=UIViewContentModeScaleAspectFill;
    
    
    [_tableView insertSubview:_View atIndex:0];
    
    
    
    
    _tableView.backgroundColor=[UIColor whiteColor];
    
      
    

    // tableHeaderView
    CustomView* tableheaderView=[[NSBundle mainBundle]loadNibNamed:@"CustomView" owner:nil options:nil][0];
    
    _tableView.tableHeaderView=tableheaderView;
    
    
  
    
    
   
    //点击滑动view
   _lineView= tableheaderView.lineView;
    
    
    //左右点击按钮
    
    [tableheaderView.leftButton setTitle:@"简介" forState:UIControlStateNormal];
    
    [tableheaderView.rightButton setTitle:@"内容" forState:UIControlStateNormal];

 
    
    //简介按钮点击
    [tableheaderView.leftButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //内容按钮点击
    [tableheaderView.rightButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    

    

    //左侧返回按钮
    [self leftBackButton];
    
    
    //右侧导航关注按钮

    ;
    
    [self.view addSubview:[self rightAttentionLabel]];

    //    naviBackButton
    
    
    
    [self isExist];
    
    
  UILabel*  TitleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 25)];
    
    TitleLabel.text=_model.title;
    
    
    self.navigationItem.titleView=TitleLabel;
    
    
 
    
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                         forBarMetrics:UIBarMetricsDefault];




}


- (UIButton*)leftBackButton{
    
    
    
    //左侧导航跳转按钮
    
    
    UIButton* button=[UIButton buttonWithType:UIButtonTypeCustom];
    
    button.frame=CGRectMake(15, 20, 30, 30);
    [button setBackgroundImage:[UIImage imageNamed:@"naviBackButton.png"] forState:UIControlStateNormal];
    
    
    [button addTarget:self action:@selector(pop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    _leftBackButton=button;
    
    [self.view bringSubviewToFront:_leftBackButton];


    return _leftBackButton;
    

    
}

- (UILabel*)rightAttentionLabel{
    
    
    _attentionLabel=[[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-50-10 , 20, 50, 25)];
    _attentionLabel.text=@"+关注";
    _attentionLabel.backgroundColor=JZJYELLOW;
    _attentionLabel.clipsToBounds=YES;
    _attentionLabel.font=[UIFont systemFontOfSize:10];
    _attentionLabel.layer.cornerRadius = 10;//圆角
    _attentionLabel.layer.borderWidth = 1.3;//边框宽度 描边
    
    _attentionLabel.textAlignment=NSTextAlignmentCenter;
    _attentionLabel.textColor=[UIColor blackColor] ;
    
    _attentionLabel.layer.borderColor = [[UIColor blackColor]CGColor];
    

    
    
    UITapGestureRecognizer* tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(thumb:)];
    
    _attentionLabel.userInteractionEnabled=YES;
    [_attentionLabel addGestureRecognizer:tap];
    

    return _attentionLabel;
    
}

- (void)isExist
{


    
    
    NSUserDefaults* userdefault=[NSUserDefaults standardUserDefaults];
    
    
    NSMutableArray* mutableArray=[userdefault objectForKey:IDArray];
    
    
    [mutableArray enumerateObjectsUsingBlock:^(NSNumber* obj, NSUInteger idx, BOOL *stop) {
        
        if ([_model.id isEqualToNumber:obj]) {
            _isSelected=YES;
            _attentionLabel.text=@"已关注";
            _attentionLabel.textColor=[UIColor whiteColor];
            
            _attentionLabel.backgroundColor=JZJLIGHTGRAY;
            
            _attentionLabel.alpha=0.5;
        }
        
    }];
    
    



}
- (void)pop:(UIButton*)sender
{

    
    [self.navigationController popViewControllerAnimated:YES];
}

//右上角单击收藏

- (void)thumb:(UIGestureRecognizer*)tap
{

    
    
    //无网络连接 无法点击
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    BOOL isConnection = 0;
    
    isConnection=[userdefault boolForKey:@"isConnection"];
    
    if (!isConnection) {
        return;
    }
    
    
    BOOL isLand=[userdefault boolForKey:ISLAND];//BOOL
    
    if (!isLand) {
        LandController* vc=[[LandController alloc]init];
        
        [self presentViewController:vc animated:YES completion:nil];
        
        
        //        [ProgressHUD showError:@"未登录" Interaction:YES];
        
        return;
    }
    

    
    
//    //无网络连接 无法点击
//    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
//    BOOL isConnection=nil;
    
    isConnection=[userdefault boolForKey:@"isConnection"];
    
    if (!isConnection) {
        return;
    }
    
    
    
//    NSUserDefaults* userdefault=[NSUserDefaults standardUserDefaults];
    
    
    NSMutableArray* mutableArray=[userdefault objectForKey:IDArray];
    
    
    
    [mutableArray enumerateObjectsUsingBlock:^(NSNumber* obj, NSUInteger idx, BOOL *stop) {
        
        if ([_model.topic[@"id"] isEqualToNumber:obj]) {
            
            _isSelected=YES;
             _isExisted=YES;

        }
        
    }];
    
    
    
    if (_isSelected==NO) {//单次收藏
        
//        JZJLog(@"%zd",_isSelected);

        [DownLoad postDataWithID:_model.id andBlock:^(id obj, NSError *error) {
            
            
            
            NSString* str=obj[@"message"];
            
            
            if ([str isEqual:@"OK"]) {
                
                [ProgressHUD show:str Interaction:YES];
                
                
                [ProgressHUD dismiss];
                
            }
            
            
            
        }];
        
        _isSelected=YES;

        
        _attentionLabel.text=@"已关注";
        _attentionLabel.textColor=[UIColor whiteColor];

        _attentionLabel.backgroundColor=JZJLIGHTGRAY;

        _attentionLabel.alpha=0.5;
        if (_isExisted==NO) {
            
            //增加id
            
            NSMutableArray *mutaArray = [[NSMutableArray alloc] init];
            [mutaArray addObjectsFromArray:mutableArray];
            
            [mutaArray addObject:_model.id];
            
            [userdefault setObject:mutaArray forKey:IDArray];
            [userdefault synchronize];
            

        }
        
        
    }else{//双次删除收藏
    
        _isSelected=NO;

    [DownLoad delteDataWithID:_model.id andBlock:^(id obj, NSError *error) {
        
        
        
        NSString* str=obj[@"message"];
        
        
        if ([str isEqual:@"OK"]) {
            
            [ProgressHUD show:str Interaction:YES];
            
            
            [ProgressHUD dismiss];
            
        }

        
    }];

        
        _attentionLabel.text=@"关注";
        _attentionLabel.textColor=JZJLABELCOLOR;
        _attentionLabel.backgroundColor=JZJYELLOW;

        _attentionLabel.alpha=1;

        
        
        
        
        
        //删除id

        
        NSMutableArray *mutaArray = [[NSMutableArray alloc] init];
        [mutaArray addObjectsFromArray:mutableArray];
        [mutaArray removeObject:_model.id];
        
        [userdefault setObject:mutaArray forKey:IDArray];
        
        
        [userdefault synchronize];
        _isExisted=NO;


    }
    
    
    
    JZJLog(@"%@",[userdefault objectForKey:IDArray]);
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    float y=scrollView.contentOffset.y;
    
    if (y<-200) {
        
        
        
        CGRect frame=_View.frame;
        
        frame.origin.y=y;
        
        frame.size.height=-y;
        
        
   
        _View.frame=frame;
      
           
    }
    

    
    
}


-(CGRect) getBarItemRc :(UIBarButtonItem *)item{
    UIView *view = [item valueForKey:@"view"];
    return [view frame];
}

//单机逆序 双击顺序 刷新cell
- (void)order:(UIButton*)sender
{
    
    static int i=1;
    i++;
    
    if (i%2) {
        //        允许编辑
       
        
        
        _i=1;
    
        
    }else {
        
      
        _i=0;

        
    }

    _currentState=JZJTableViewState_showContent;

    
    [self loadData];

}

- (void)click:(UIButton*)sender
{
    

    switch (sender.tag) {
        case 1000:
            
          
            
            self.currentState = JZJTableViewState_showIntroduce;
            
                if (_currentState==JZJTableViewState_showIntroduce) {
            
                    [UIView animateWithDuration:0.1 animations:^{
            
                        _lineView.frame=CGRectMake(0, 30, self.view.frame.size.width/2, 2);
                        
                    }];
                    
                    
                    
                    
                }

            
            [_tableView reloadData];
     
            
            
    
            break;
            
        case 2000:
            
            self.currentState = JZJTableViewState_showContent;

            
            
            if (_currentState==JZJTableViewState_showContent) {
                
                [UIView animateWithDuration:0.1 animations:^{
                    
                    _lineView.frame=CGRectMake(self.view.frame.size.width/2, 30, self.view.frame.size.width/2, 2);
                    
                }];
            }
            
            
            [_tableView reloadData];

            break;
    }


}


//单机label触发事件

- (void)tap:(UITapGestureRecognizer*)tap
{


    
    JZJLog(@"xx");
}


#pragma mark --UITableViewDataSource



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (_currentState==JZJTableViewState_showIntroduce) {
    
        
        
        return 1;
        
    }else
    {
    
        return _dataArray.count;

    }
    
    
    
    
}


#pragma mark --UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (self.currentState==JZJTableViewState_showContent) {
        
        
        return 90;
        
    }
    else if(self.currentState==JZJTableViewState_showIntroduce)
    {
        
        
        
        return 44;
    }
    
    return 0;}






- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_currentState==JZJTableViewState_showContent) {
        
        
        NavisearchCell * cell=[tableView dequeueReusableCellWithIdentifier:@"ThirdNavisearchCell"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;//取消选中风格

        
        if (!cell) {
            
            
            
            cell=[[NSBundle mainBundle]loadNibNamed:@"ThirdNavisearchCell" owner:nil options:nil][0];
            
            
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
        
        }
        
        
        //刷新
        
        Model* model=_dataArray[indexPath.row];
        
        
        [cell ThirdNaviSearchControllerrefreshWithModel:model WithIndexPath:indexPath];
        
       
        return cell;
        
    }
    else
    {
        

        UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"ID"];
        
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"];
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            

        }
        
        
        cell.selectionStyle=UITableViewRowAnimationNone;//无点击效果
        
        
        [cell.imageView sd_setImageWithURL:_introductionModel.user[@"avatar_url"] placeholderImage:[UIImage imageNamed:@"placehonderICon.png"]];
        
        
        //icon 圆角 描边
        cell.imageView.layer.cornerRadius=21;
        cell.imageView.clipsToBounds=YES;
        cell.imageView.layer.borderWidth=0.5;
        cell.imageView.layer.borderColor=[SEPARATORCOLOR CGColor];
        cell.textLabel.text=_introductionModel.user[@"nickname"];
        
        
        return cell;
    }
    
    return nil;

    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    
    if (_currentState==JZJTableViewState_showIntroduce) {
    
        IntroduceController* vc=[[IntroduceController alloc]init];
        
        
        Model* model=[[Model alloc]init];
        [model setValuesForKeysWithDictionary:_introductionModel.user];
        vc.model=model;
        

        vc.hidesBottomBarWhenPushed=YES;
        
        [self.navigationController pushViewController:vc animated:YES];
    
        
        
        
        
        
        
    }else{
    
    WebViewController* vc=[[WebViewController alloc]init];
    
    Model* model=_dataArray[indexPath.row];
        

        
        model.value=model.id;
    
    

    vc.model=model;
        
        
    vc.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:vc animated:YES];
    
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    
    
    if (self.currentState==JZJTableViewState_showContent) {
        
        
        return 30;
        
    }
    else if(self.currentState==JZJTableViewState_showIntroduce)
    {
        
        return 30;
    }

    return 0;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{

    return 1;

}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
        
        if (self.currentState==JZJTableViewState_showContent) {
            
            UITableViewHeaderFooterView* view=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
//            CustomView* view=[tableView dequeueReusableCellWithIdentifier:@"CustomView2"];
            if (!view) {

            
//            view=[[NSBundle mainBundle]loadNibNamed:@"CustomView2" owner:nil options:nil][0];
                
                
         
                
                view=[[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"headerView"];

                view.contentView.backgroundColor=[UIColor whiteColor];

                UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(7, 5, 100, 20)];
                label.text=@"专题列表";
                label.textColor=JZJLABELCOLOR;
                label.font=[UIFont systemFontOfSize:12];
                
                [view.contentView addSubview:label];
                
                
                //点击顺序切换按钮
                UIButton* orderButton=[UIButton buttonWithType:UIButtonTypeCustom];
                
                orderButton.frame=CGRectMake(SCREEN_WIDTH-80, 5, 40, 20);
                
                orderButton.titleLabel.font=[UIFont systemFontOfSize:12];
                [orderButton setTitle:self.titleStr forState:UIControlStateNormal];
//                [orderButton setTitle:@"hhh" forState:UIControlStateSelected];
                [orderButton setTitleColor:JZJLABELCOLOR forState:UIControlStateNormal];
                
                [orderButton addTarget:self action:@selector(orderMake:) forControlEvents:UIControlEventTouchUpInside];
                
                [view.contentView addSubview:orderButton];
                
                self.orderButton = orderButton;
                
                
                
                //点击顺序切换图片显示按钮

                UIButton* orderImageButton=[UIButton buttonWithType:UIButtonTypeCustom];
                
                orderImageButton.frame=CGRectMake(SCREEN_WIDTH-40, 5, 20, 20);

                
                [orderImageButton setBackgroundImage:[UIImage imageNamed:self.isSeleted ? @"order1" : @"order2"] forState:UIControlStateNormal];
                
                
                [view.contentView addSubview:orderImageButton];
                
                
                

                
            
            }
            
            return view;
            
            
        }
        else
        {
        
            
            CustomView* view=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"CustomView3"];
            if (!view) {
                

            
                
            view=[[NSBundle mainBundle]loadNibNamed:@"CustomView3" owner:nil options:nil][0];

                [view refreshHeaderLabelWithModel:_introductionModel];

                
            }
            
            
            return view;
            
        }
    
    
    
    return nil;



}

- (void)orderMake:(UIButton*)sender
{

    
    [self loadData];
    
    static int i = 1;
    i++;
    if (i % 2) {
        _i=0;
        
        self.titleStr = @"顺序";
        self.isSeleted = !_isSeleted;
    } else {
        
        _i=1;
        self.titleStr = @"逆序";
        self.isSeleted = !_isSeleted;

    }
    
    
}



@end
